﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

using System.Data.SqlClient;
using System.Web.Configuration;
using System.Security.Cryptography;
using System.Text;

namespace HiViLicenseManage
{
	public partial class GetKey : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			try
			{
				SucsessAcceptKey.InnerText = "";
				lblWarning.Text = "";

				if (!IsPostBack)
				{
					LoadInfomation();

					Session["sKey1"] = "";
					Session["sKey2"] = "";
					Session["sKey3"] = "";
					Session["sKey4"] = "";
				}
			}
			catch
			{
				Response.Redirect("~/Error.aspx", false);
			}
		}

		private void LoadInfomation()
		{
			txtResult.Text = "";
			lblWarning.Text = "";
			txtResult.ReadOnly = true;

			SqlConnection appConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["appconn"].ConnectionString);
			appConn.Open();

			SqlCommand sqlComm1 = new SqlCommand("SELECT FK_SoftwareID, SoftwareName FROM vwAgentKey WHERE UPPER(FK_AgentID) = @FK_AgentID AND Status = 'True'", appConn);
			sqlComm1.CommandType = CommandType.Text;
			sqlComm1.Parameters.Add("@FK_AgentID", SqlDbType.VarChar).Value = User.Identity.Name.ToUpper();
			SqlDataAdapter sqlDA1 = new SqlDataAdapter();
			sqlDA1.SelectCommand = sqlComm1;
			DataTable dtAgentKey = new DataTable();
			sqlDA1.Fill(dtAgentKey);

			drProduct.DataSource = dtAgentKey;
			drProduct.DataValueField = "FK_SoftwareID";
			drProduct.DataTextField = "SoftwareName";
			drProduct.DataBind();

			SqlCommand sqlComm2 = new SqlCommand("SELECT KeyTypeID, KeyTypeName, Days FROM KeyType", appConn);
			sqlComm2.CommandType = CommandType.Text;
			SqlDataAdapter sqlDA2 = new SqlDataAdapter();
			sqlDA2.SelectCommand = sqlComm2;
			DataTable dtKeyType = new DataTable();
			sqlDA2.Fill(dtKeyType);

			drKeyType.DataSource = dtKeyType;
			drKeyType.DataValueField = "KeyTypeID";
			drKeyType.DataTextField = "KeyTypeName";
			drKeyType.DataBind();

			appConn.Close();

			Session["dtKeyType"] = dtKeyType;
		}

		protected void btnGenKey_Click(object sender, EventArgs e)
		{
			try
			{
				if (drProduct.Items.Count <= 0 || drProduct.SelectedValue == null)
				{
					lblWarning.Text = "(*) Chưa chọn phần mềm";
					return;
				}
				if (drKeyType.Items.Count <= 0 || drKeyType.SelectedValue == null)
				{
					lblWarning.Text = "(*) Chưa chọn loại key";
					return;
				}

				KeyGenerator.SetRandomData(true, false, true);

				string sKey1, sKey2, sKey3, sKey4;
				do
				{
					sKey1 = KeyGenerator.Generate(5);
					sKey2 = KeyGenerator.Generate(5);
					sKey3 = KeyGenerator.Generate(5);
					sKey4 = KeyGenerator.Generate(5);
				} while (CheckKeyExist(sKey1 + sKey2 + sKey3 + sKey4) == true);
				txtResult.Text = sKey1 + "  " + sKey2 + "  " + sKey3 + "  " + sKey4;

				Session["sKey1"] = sKey1;
				Session["sKey2"] = sKey2;
				Session["sKey3"] = sKey3;
				Session["sKey4"] = sKey4;
			}
			catch
			{
				Response.Redirect("~/Error.aspx", false);
			}
		}

		protected void btnAcceptKey_Click(object sender, EventArgs e)
		{
			try
			{
				string sKey = Session["sKey1"].ToString() + Session["sKey2"].ToString() + Session["sKey3"].ToString() + Session["sKey4"].ToString();

				if (CheckSaveValidKey(sKey, User.Identity.Name, drProduct.SelectedValue) == false)
					return;

				int days = Convert.ToInt32(((DataTable)Session["dtKeyType"]).Rows[drKeyType.SelectedIndex]["Days"]);

				SqlConnection appConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["appconn"].ConnectionString);
				appConn.Open();

				SqlCommand sqlComm = new SqlCommand("INSERT INTO LicenseKey (LicenseKey, FK_SoftwareID, Days, FK_AgentID, DateCreated, Status) VALUES (@LicenseKey, @FK_SoftwareID, @Days, @FK_AgentID, @DateCreated, @Status)", appConn);
				sqlComm.CommandType = CommandType.Text;
				sqlComm.Parameters.Add("@LicenseKey", SqlDbType.VarChar).Value = sKey;
				sqlComm.Parameters.Add("@FK_SoftwareID", SqlDbType.VarChar).Value = drProduct.SelectedValue;
				sqlComm.Parameters.Add("@Days", SqlDbType.Int).Value = days;
				sqlComm.Parameters.Add("@FK_AgentID", SqlDbType.VarChar).Value = User.Identity.Name.ToUpper();
				sqlComm.Parameters.Add("@DateCreated", SqlDbType.DateTime).Value = DateTime.Now;
				sqlComm.Parameters.Add("@Status", SqlDbType.VarChar).Value = "1";
				if (sqlComm.ExecuteNonQuery() > 0)
				{
					lblWarning.Text = "";
					txtResult.Text = "";
					Session["sKey1"] = "";
					Session["sKey2"] = "";
					Session["sKey3"] = "";
					Session["sKey4"] = "";
					SucsessAcceptKey.InnerText = "  Nhận key thành công!";
				}
				appConn.Close();
			}
			catch
			{
				txtResult.Text = "";
				Session["sKey1"] = "";
				Session["sKey2"] = "";
				Session["sKey3"] = "";
				Session["sKey4"] = "";
				Response.Redirect("~/Error.aspx", false);
			}
		}

		private bool CheckKeyExist(string sKey)
		{
			SqlConnection appConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["appconn"].ConnectionString);
			appConn.Open();

			SqlCommand sqlComm = new SqlCommand("SELECT LicenseKey FROM LicenseKey WHERE LicenseKey = @LicenseKey", appConn);
			sqlComm.CommandType = CommandType.Text;
			sqlComm.Parameters.Add("@LicenseKey", SqlDbType.VarChar).Value = sKey;
			SqlDataAdapter sqlDA = new SqlDataAdapter();
			sqlDA.SelectCommand = sqlComm;
			DataTable dtKey = new DataTable();
			sqlDA.Fill(dtKey);

			appConn.Close();

			if (dtKey.Rows.Count > 0)
				return true;
			else
				return false;
		}

		private int NumberKeyAgent(string sAgent, string sSoftware)
		{
			SqlConnection appConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["appconn"].ConnectionString);
			appConn.Open();

			SqlCommand sqlComm = new SqlCommand("SELECT NumberKey FROM vwAgentKey WHERE UPPER(FK_AgentID) = @FK_AgentID AND FK_SoftwareID = @FK_SoftwareID AND Status = 'True'", appConn);
			sqlComm.CommandType = CommandType.Text;
			sqlComm.Parameters.Add("@FK_AgentID", SqlDbType.VarChar).Value = sAgent.ToUpper();
			sqlComm.Parameters.Add("@FK_SoftwareID", SqlDbType.VarChar).Value = sSoftware;
			SqlDataAdapter sqlDA = new SqlDataAdapter();
			sqlDA.SelectCommand = sqlComm;
			DataTable dtNumber = new DataTable();
			sqlDA.Fill(dtNumber);

			appConn.Close();

			if (dtNumber.Rows.Count > 0)
				return Convert.ToInt32(dtNumber.Rows[0]["NumberKey"]);
			else
				return 0;
		}

		private int NumberKeyRegisted(string sAgent, string sSoftware)
		{
			DateTime dFirst;
			DateTime dLast;
			FirstAndLastDayOfMonth(DateTime.Now, out dFirst, out dLast);

			SqlConnection appConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["appconn"].ConnectionString);
			appConn.Open();

			SqlCommand sqlComm = new SqlCommand("SELECT LicenseKey FROM LicenseKey WHERE UPPER(FK_AgentID) = @FK_AgentID AND FK_SoftwareID = @FK_SoftwareID AND DateCreated >= @DateCreated1 AND DateCreated <= @DateCreated2", appConn);
			sqlComm.CommandType = CommandType.Text;
			sqlComm.Parameters.Add("@FK_AgentID", SqlDbType.VarChar).Value = sAgent.ToUpper();
			sqlComm.Parameters.Add("@FK_SoftwareID", SqlDbType.VarChar).Value = sSoftware;
			sqlComm.Parameters.Add("@DateCreated1", SqlDbType.DateTime).Value = dFirst;
			sqlComm.Parameters.Add("@DateCreated2", SqlDbType.DateTime).Value = dLast;
			SqlDataAdapter sqlDA = new SqlDataAdapter();
			sqlDA.SelectCommand = sqlComm;
			DataTable dtKey = new DataTable();
			sqlDA.Fill(dtKey);

			appConn.Close();

			return dtKey.Rows.Count;
		}

		public void FirstAndLastDayOfMonth(DateTime recent, out DateTime first, out DateTime last)
		{
			first = new DateTime(recent.Year, recent.Month, 1);
			DateTime nextFirst;
			if (first.Month == 12)
				nextFirst = new DateTime(first.Year + 1, 1, 1);
			else
				nextFirst = new DateTime(first.Year, first.Month + 1, 1);
			last = nextFirst.AddDays(-1);
		}

		private bool CheckSaveValidKey(string key, string userid, string software)
		{
			if (drProduct.Items.Count <= 0 || drProduct.SelectedValue == null)
			{
				lblWarning.Text = "(*) Chưa chọn phần mềm";
				return false;
			}

			if (drKeyType.Items.Count <= 0 || drKeyType.SelectedValue == null)
			{
				lblWarning.Text = "(*) Chưa chọn loại key";
				return false;
			}

			if (txtResult.Text.Trim() == "")
			{
				lblWarning.Text = "(*) Chưa sinh key";
				return false;
			}
			if (key.Length != 20)
			{
				lblWarning.Text = "(*) Key không hợp lệ";
				return false;
			}
			if (CheckKeyExist(key) == true)
			{
				lblWarning.Text = "(*) Key đã được đăng kí bởi đơn vị khác, tạo lại key mới";
				return false;
			}
			if (NumberKeyRegisted(userid, software) >= NumberKeyAgent(userid, software))
			{
				lblWarning.Text = "(*) Đã vượt quá số lượng key giới hạn trong tháng";
				return false;
			}
			return true;
		}
	}
}
